package com.bw.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.bw.pojo.system.Admin;
import com.bw.service.system.AdminService;
import com.bw.service.system.ResourceService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserDetailsServiceImpl implements UserDetailsService {

    @Reference
    private AdminService adminService;
    @Reference
    private ResourceService resourceService;

    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("经过了UserDetailsServiceImpl");
        //查询管理员
        Map map = new HashMap();
        map.put("loginName", s);
        map.put("status", 1);
        List<Admin> list = adminService.findList(map);
        if (list.size()==0) {
            return null;
        }
        //构建角色集合，项目中此处应该是根据用户名查询用户的角色列表
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        //grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        //grantedAuthorities.add(new SimpleGrantedAuthority("goods_add"));
        //grantedAuthorities.add(new SimpleGrantedAuthority("goods_edit"));
        //构建权限列表
        List<String> resKeys = resourceService.getResKeys(s);
        for (String resKey : resKeys) {
            grantedAuthorities.add(new SimpleGrantedAuthority(resKey));
        }
        return new User(s,list.get(0).getPassword(),grantedAuthorities);
    }
}